package com.qingyun.common.utils;

import cn.hutool.core.util.ObjectUtil;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;

/**
 * @Classname QrcodeGeneratorUtils
 * @Author dyh
 * @Date 2021/6/25 15:21
 */
public class QrcodeGeneratorUtils {

    public static void createBaseQrcodeResponse(String url, HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            response.setContentType("image/jpeg");
            outputStream = response.getOutputStream();
            new SimpleQrcodeGenerator().generate(url).toStream(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (ObjectUtil.isNotNull(outputStream)) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String  createBaseQrcodeBase64(String url) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
           new SimpleQrcodeGenerator().generate(url).toStream(byteArrayOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] bytes = byteArrayOutputStream.toByteArray();
            return Base64.getEncoder().encodeToString(bytes);
        }


    }
}
